package com.mmy.fta.trade.server.service.impl;

import com.mmy.fta.cargo.api.facade.CargoService;
import com.mmy.fta.cargo.api.model.CargoInfoDTO;
import com.mmy.fta.coldtruck.api.ColdTruckService;
import com.mmy.fta.coldtruck.api.dto.ColdTruckTHData;
import com.mmy.fta.trade.server.dao.OrderDao;
import com.mmy.fta.trade.server.dto.CanceledOrderDTO;
import com.mmy.fta.trade.server.dto.CargoOrderDTO;
import com.mmy.fta.trade.server.dto.CompletedOrderDTO;
import com.mmy.fta.trade.server.dto.TransportOrderDTO;
import com.mmy.fta.trade.server.dto.ShipperOrderDTO;
import com.mmy.fta.trade.server.entity.OrderEntity;
import com.mmy.fta.trade.server.request.AgreeOrderRequest;
import com.mmy.fta.trade.server.request.CancelOrderRequest;
import com.mmy.fta.trade.server.request.CanceledOrderRequest;
import com.mmy.fta.trade.server.request.ColdTruckRequest;
import com.mmy.fta.trade.server.request.CompletedOrderRequest;
import com.mmy.fta.trade.server.response.ColdTruckResponse;
import com.mmy.fta.trade.server.response.CreatOrderResponse;
import com.mmy.fta.trade.server.request.LoadOrderRequest;
import com.mmy.fta.trade.server.request.PayDepositCheckRequest;
import com.mmy.fta.trade.server.request.ReceiveOrderRequest;
import com.mmy.fta.trade.server.request.RefuseOrderRequest;
import com.mmy.fta.trade.server.request.RepublishCargoRequest;
import com.mmy.fta.trade.server.request.TransportOrderRequest;
import com.mmy.fta.trade.server.request.PreCreatOrderRequest;
import com.mmy.fta.trade.server.request.UnloadOrderRequest;
import com.mmy.fta.trade.server.request.CreatOrderRequest;
import com.mmy.fta.trade.server.response.PreCreatOrderResponse;
import com.mmy.fta.trade.server.service.OrderService;
import com.mmy.fta.trade.server.service.PaymentService;
import com.mmy.fta.trade.server.util.SnowflakeIdUtils;
import com.mmy.fta.trade.server.websocket.ShipperWebSocketTest;
import com.mmy.fta.usercenter.api.MembershipService;
import com.mmy.fta.usercenter.api.UserService;
import com.mmy.fta.usercenter.dto.DriverDTO;
import com.mmy.fta.usercenter.dto.ShipperDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author qiang.lin
 * @since 2021/10/22
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Reference
    UserService userService;

    @Reference
    CargoService cargoService;

    @Reference
    MembershipService membershipService;

    @Autowired
    OrderDao orderDao;

    @Autowired
    PaymentService paymentService;

//    @Autowired
//    MessageProduceService messageProduceService;

//    @MessageReference(key="fta-trade-producer")
//    Producer orderProducer;

    @Autowired
    ShipperWebSocketTest shipperWebSocket;


//    @Lock(key = "trade-redis",scene = "fta-training-driverCreateOrder")
//    private LockFactory lockClient;

    @Reference
    ColdTruckService coldTruckService;

    public CargoInfoDTO queryCargoInfobyCargoId(String cargoId){
        return cargoService.queryCargoInfobyCargoId(cargoId);
    }

    public DriverDTO queryDriverInfoByOpenId(String driverOpenId){
        return userService.queryDriverInfoByOpenId(driverOpenId).getData();
    }

    public ShipperDTO queryByShipperIdentityId(String shipperIdNo){
        return userService.queryByShipperIdentityId(shipperIdNo).getData();
    }

    /**
     * 司机点击去抢单
     * @param preCreatOrderRequest
     * @return
     */
    @Override
    public PreCreatOrderResponse preCreateOrder(PreCreatOrderRequest preCreatOrderRequest) {
        PreCreatOrderResponse preCreatOrderResponse = new PreCreatOrderResponse();

        //cargo
        CargoInfoDTO cargoInfoDTO = queryCargoInfobyCargoId(preCreatOrderRequest.getCargoId());
        CargoOrderDTO cargoOrderDTO = new CargoOrderDTO();
        BeanUtils.copyProperties(cargoInfoDTO,cargoOrderDTO);

        //净得运费
        if(cargoInfoDTO.getNeedReturnDeposit() == 0){
            Integer netDeposit = cargoInfoDTO.getCargoFee()-cargoInfoDTO.getDeposit();
            cargoOrderDTO.setNetDeposit(netDeposit);
            cargoOrderDTO.setGuaranteeDescription("0");
        }else {
            Integer netDeposit = cargoInfoDTO.getCargoFee();
            cargoOrderDTO.setNetDeposit(netDeposit);
            cargoOrderDTO.setGuaranteeDescription("1");
        }
        cargoOrderDTO.setIsBetterCargo("0");
        preCreatOrderResponse.setCargoOrderDTO(cargoOrderDTO);

        //shipper
        ShipperDTO shipperDTO = queryByShipperIdentityId(cargoInfoDTO.getShipperIdNo());
        ShipperOrderDTO shipperOrderDTO = new ShipperOrderDTO();
        BeanUtils.copyProperties(shipperDTO,shipperOrderDTO);

        //好评率
        if(null == shipperDTO.getTradeTimes() ||shipperDTO.getTradeTimes() == 0 ){
            shipperOrderDTO.setPraiseRate(0);
        }else {
            Integer praiseRate = (int)(shipperDTO.getDeliverys()/shipperDTO.getTradeTimes());
            shipperOrderDTO.setPraiseRate(praiseRate);
        }
        preCreatOrderResponse.setShipperOrderDTO(shipperOrderDTO);

        return preCreatOrderResponse;
    }


    /**
     * 司机下单插入订单表
     * @param creatOrderRequest
     * @param cargoInfoDTO
     * @param driverDTO
     * @param orderNumber
     * @param payId
     * @return
     */

    public int insertOrderByDriver(CreatOrderRequest creatOrderRequest,CargoInfoDTO cargoInfoDTO,DriverDTO driverDTO,String orderNumber,
                                   String payId){
        //插入order表
        OrderEntity orderEntity = new OrderEntity();

        orderEntity.setOrderNumber(orderNumber);

        orderEntity.setPayId(payId);

        orderEntity.setCargoId(creatOrderRequest.getCargoId());
        orderEntity.setIsUseCoupon(creatOrderRequest.getPreferenceType());
        orderEntity.setConsignorUserId(cargoInfoDTO.getShipperIdNo());
        //货主openId
        orderEntity.setConsignorOpenid(cargoInfoDTO.getOpenId());

        orderEntity.setCouponType(0);

        if(creatOrderRequest.getPreferenceType()==1){
            orderEntity.setCouponId(1);
            //免佣-1
        }else if(creatOrderRequest.getPreferenceType()==2){
            orderEntity.setCouponId(Integer.valueOf(creatOrderRequest.getCouponId()));
            //券-1
        }else if(creatOrderRequest.getPreferenceType() == 3){
            orderEntity.setCouponId(0);
        }else {
            orderEntity.setCouponId(-1);
        }
        orderEntity.setConsignorUserId(cargoInfoDTO.getShipperIdNo());
        orderEntity.setCarrierUserId(driverDTO.getIdentityNo());
        orderEntity.setCarrierOpenid(creatOrderRequest.getOpenId());
        orderEntity.setDriverPayDeposit(cargoInfoDTO.getDeposit());
        orderEntity.setIsBackDeposit(cargoInfoDTO.getNeedReturnDeposit());
        orderEntity.setTotalFreightAmount(cargoInfoDTO.getCargoFee());
        orderEntity.setStatus(1);
        orderEntity.setAddTime(new Date());
        orderEntity.setUpdateTime(new Date());
        orderEntity.setDriverServiceCharge(Double.valueOf(cargoInfoDTO.getEstimateDistance()));
        orderEntity.setOrderType(creatOrderRequest.getNetDeposit());

        orderEntity.setCarrierMode(0);

        return orderDao.insert(orderEntity);
    }




   //todo
    // mi deng
    /**
     * 司机下单，生成订单，支付流水
     * @param creatOrderRequest
     * @return
     */
//    @DistributedTransaction(name = "fta-trade-driver-createOrder")
//    @Idempotent(scene = "fta-trade-driver-createOrder",storageName = "trade-redis")
    @Override
    public CreatOrderResponse createTransportOrderByDriver(CreatOrderRequest creatOrderRequest) {
        CreatOrderResponse creatOrderResponse = new CreatOrderResponse();

        PayDepositCheckRequest payDepositCheckRequest = new PayDepositCheckRequest();
        BeanUtils.copyProperties(creatOrderRequest,payDepositCheckRequest);

//        AtomicReference<CargoInfoDTO> cargoInfoDTO = new AtomicReference<>(new CargoInfoDTO());
//        AtomicReference<DriverDTO> driverDTO = new AtomicReference<>(new DriverDTO());
//        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
//                6,
//                10,
//                5,
//                TimeUnit.MILLISECONDS,
//                new ArrayBlockingQueue<Runnable>(6),
//                new ThreadPoolExecutor.CallerRunsPolicy()
//        );
//
//        CompletableFuture<Void> cargoInfoDTOFuture = CompletableFuture.runAsync(() -> {
//             cargoInfoDTO.set(queryCargoInfobyCargoId(creatOrderRequest.getCargoId()));
//        },threadPoolExecutor);
//
//        CompletableFuture<Void> driverDTOFuture = CompletableFuture.runAsync(() -> {
//             driverDTO.set(queryDriverInfoByOpenId(creatOrderRequest.getOpenId()));
//        },threadPoolExecutor);
//
//        CompletableFuture.allOf(cargoInfoDTOFuture,driverDTOFuture);

        CargoInfoDTO cargoInfoDTO = queryCargoInfobyCargoId(creatOrderRequest.getCargoId());
        DriverDTO driverDTO = queryDriverInfoByOpenId(creatOrderRequest.getOpenId());

        boolean checkPay = paymentService.payDepositCheckForDriver(payDepositCheckRequest, cargoInfoDTO);


        String orderNumber =  String.valueOf(new SnowflakeIdUtils(1, 1).nextId());
        String payId =  String.valueOf(new SnowflakeIdUtils(2, 1).nextId());

        if (checkPay) {
//            DistributedLock lock = lockClient.getLock("fta-training-cargo" + creatOrderRequest.getCargoId());
            try{
//                if(lock.tryLock()){
                if(true){
                    log.info("司机：{} 抢到货：{}",creatOrderRequest.getOpenId(),creatOrderRequest.getCargoId());

                    CargoInfoDTO cargoInfoDTO1 = queryCargoInfobyCargoId(creatOrderRequest.getCargoId());
                    if(cargoInfoDTO1.getCargoStatus() != 10){
                        creatOrderResponse.setIsSuccess(false);
                        return creatOrderResponse;
                    }
                    //插入订单表
                    insertOrderByDriver(creatOrderRequest, cargoInfoDTO, driverDTO,orderNumber,payId);

                    log.info("司机：{}，货：{}，订单：{}",creatOrderRequest.getOpenId(),creatOrderRequest.getCargoId(),orderNumber);
                    //货源下架，通知货主，告知司机结果
                    cargoService.cargoStatusEdit(creatOrderRequest.getCargoId(),20);

                    log.info("payId:{}",payId);
                    //支付流水
                    paymentService.payDepositByDriver(payId,creatOrderRequest.getOpenId(),orderNumber, cargoInfoDTO.getDeposit());

//                    Message orderNumberMsg = Message.normal("fta-training-trade").tag("fta-order").payload(orderNumber).build();
//                   Result mqRes = orderProducer.send(orderNumberMsg);
//
//                    if (mqRes.getStatus() == ResultStatus.SEND_OK){
//                        log.info("MQ-发送成功-fta-orderNumber:{}",orderNumber);
//                    }else {
//                        log.info("MQ-发送失败-fta-orderNumber:{}",orderNumber);
//                    }

                    creatOrderResponse.setIsSuccess(true);

                    return creatOrderResponse;
                }else {
                    creatOrderResponse.setIsSuccess(false);
                    return creatOrderResponse;
                }
            }
            finally {
//                lock.unlock();
            }
        }
        else {
            creatOrderResponse.setIsSuccess(false);
            return creatOrderResponse;
        }
    }


    /**
     * 司机运输中页面
     * @param orderInTransportRequest
     * @return
     */
    @Override
    public List<TransportOrderDTO> queryTransportOrdersByDriver(TransportOrderRequest orderInTransportRequest) {
        List<OrderEntity> orders= orderDao.queryTransportOrderByDriver(orderInTransportRequest.getOpenId());

        List<TransportOrderDTO> transportOrderDTOs = new ArrayList<>(orders.size());
        for(OrderEntity order:orders){
            TransportOrderDTO transportOrderDTO = new TransportOrderDTO();

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String addTime = dateFormat.format(order.getAddTime());
            transportOrderDTO.setAddTime(addTime);
            transportOrderDTO.setNetDeposit(order.getOrderType());
            BeanUtils.copyProperties(order,transportOrderDTO);

            ShipperDTO shipperDTO = queryByShipperIdentityId(order.getConsignorUserId());
            if(Objects.nonNull(shipperDTO)){
                transportOrderDTO.setShipperName(shipperDTO.getUserName());
                transportOrderDTO.setShipperTelephone(shipperDTO.getTelephone());
            }



            CargoInfoDTO cargoInfoDTO = queryCargoInfobyCargoId(order.getCargoId());
            log.info("transportOrderDTOs:{}",transportOrderDTOs.size());
            if(Objects.nonNull(cargoInfoDTO)){
                BeanUtils.copyProperties(cargoInfoDTO,transportOrderDTO);
            }



            transportOrderDTOs.add(transportOrderDTO);
        }
        return transportOrderDTOs;
    }

    /**
     * 货主运输中页面
     * @param orderInTransportRequest
     * @return
     */
    @Override
    public List<TransportOrderDTO> queryTransportOrdersByShipper(TransportOrderRequest orderInTransportRequest) {
        ShipperDTO shipperDTO = userService.queryByOpenId(orderInTransportRequest.getOpenId()).getData();
        boolean isColdMember = userService.queryShipperIsColdMember(orderInTransportRequest.getOpenId());

        isColdMember = true;

        List<OrderEntity> orders= orderDao.queryTransportOrderByShipper(orderInTransportRequest.getOpenId());

        List<TransportOrderDTO> orderInTransportDTOS = new ArrayList<>(orders.size());

        for(OrderEntity order:orders){
            TransportOrderDTO transportOrderDTO = new TransportOrderDTO();

            transportOrderDTO.setColdMember(isColdMember);

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String addTime = dateFormat.format(order.getAddTime());
            transportOrderDTO.setAddTime(addTime);
            transportOrderDTO.setNetDeposit(order.getOrderType());
            BeanUtils.copyProperties(order,transportOrderDTO);

            DriverDTO driverDTO = queryDriverInfoByOpenId(order.getCarrierOpenid());
            transportOrderDTO.setDriverName(driverDTO.getUserName());
            transportOrderDTO.setDriverTelephone(driverDTO.getTelephone());

            BeanUtils.copyProperties(shipperDTO,transportOrderDTO);
            transportOrderDTO.setShipperName(shipperDTO.getUserName());
            transportOrderDTO.setShipperTelephone(shipperDTO.getTelephone());

            CargoInfoDTO cargoInfoDTO = cargoService.queryCargoInfobyCargoId(order.getCargoId());
            BeanUtils.copyProperties(cargoInfoDTO,transportOrderDTO);

            if(isColdMember){
                if(Objects.equals(cargoInfoDTO.getTruckType(),"冷藏车")){
                    transportOrderDTO.setColdTruck(true);
                }
                //todo
                transportOrderDTO.setColdTruck(true);
            }
            orderInTransportDTOS.add(transportOrderDTO);
        }
        return orderInTransportDTOS;
    }


    /**
     * 司机已取消订单列表
     * @param canceledOrderRequest
     * @return
     */
    @Override
    public List<CanceledOrderDTO> getCanceledOrdersByDriver(CanceledOrderRequest canceledOrderRequest) {
        List<OrderEntity> orders= orderDao.queryCanceledOrdersByDriver(canceledOrderRequest.getOpenId());

        List<CanceledOrderDTO> canceledOrdersDTO = new ArrayList<>(orders.size());
        for(OrderEntity order:orders){
            CanceledOrderDTO canceledOrderDTO = new CanceledOrderDTO();

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String addTime = dateFormat.format(order.getAddTime());
            canceledOrderDTO.setAddTime(addTime);
            BeanUtils.copyProperties(order,canceledOrderDTO);

            BeanUtils.copyProperties(order,canceledOrderDTO);
            canceledOrderDTO.setCancelStatus(order.getInvoiceType());

            ShipperDTO shipperDTO = userService.queryByShipperIdentityId(order.getConsignorUserId()).getData();
            if(Objects.nonNull(shipperDTO)){
                BeanUtils.copyProperties(shipperDTO,canceledOrderDTO);
                canceledOrderDTO.setShipperName(shipperDTO.getUserName());
                canceledOrderDTO.setShipperTelephone(shipperDTO.getTelephone());
            }


            CargoInfoDTO cargoInfoDTO = cargoService.queryCargoInfobyCargoId(order.getCargoId());
            BeanUtils.copyProperties(cargoInfoDTO,canceledOrderDTO);

            if(1 == order.getInvoiceType() ){
                canceledOrderDTO.setMsg("您已取消该订单");
            }
            if(2 == order.getInvoiceType()){
                canceledOrderDTO.setMsg("货主已取消该订单");
            }
            canceledOrdersDTO.add(canceledOrderDTO);
        }
        return canceledOrdersDTO;
    }

    /**
     * 货主已取消列表
     * @param canceledOrderRequest
     * @return
     */
    @Override
    public List<CanceledOrderDTO> getCanceledOrdersByShipper(CanceledOrderRequest canceledOrderRequest) {
        ShipperDTO shipperDTO = userService.queryByOpenId(canceledOrderRequest.getOpenId()).getData();

        List<OrderEntity> orders= orderDao.queryCanceledOrdersByShipper(shipperDTO.getIdentityNo());

        List<CanceledOrderDTO> canceledOrdersDTO = new ArrayList<>(orders.size());
        for(OrderEntity order:orders){
            CanceledOrderDTO canceledOrderDTO = new CanceledOrderDTO();

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String addTime = dateFormat.format(order.getAddTime());

            canceledOrderDTO.setAddTime(addTime);
            BeanUtils.copyProperties(order,canceledOrderDTO);

            canceledOrderDTO.setCancelStatus(order.getInvoiceType());

            DriverDTO driverDTO = userService.queryDriverInfoByOpenId(order.getCarrierOpenid()).getData();
            canceledOrderDTO.setDriverTelephone(driverDTO.getTelephone());
            canceledOrderDTO.setDriverName(driverDTO.getUserName());

            CargoInfoDTO cargoInfoDTO = cargoService.queryCargoInfobyCargoId(order.getCargoId());
            BeanUtils.copyProperties(cargoInfoDTO,canceledOrderDTO);

            if(2 == order.getInvoiceType() ){
                canceledOrderDTO.setMsg("您已取消该订单");
            }
            if(1 == order.getInvoiceType()){
                canceledOrderDTO.setMsg("司机已取消该订单");
            }
            canceledOrdersDTO.add(canceledOrderDTO);
        }
        return canceledOrdersDTO;
    }

    /**
     * 司机已完成列表
     * @param completedOrderRequest
     * @return
     */
    @Override
    public List<CompletedOrderDTO> getCompletedOrdersByDriver(CompletedOrderRequest completedOrderRequest) {
        List<OrderEntity> orders= orderDao.queryCompletedOrdersByDriver(completedOrderRequest.getOpenId());

        List<CompletedOrderDTO> completedOrderDTOS = new ArrayList<>(orders.size());
        for(OrderEntity order:orders){
            CompletedOrderDTO completedOrderDTO = new CompletedOrderDTO();

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String addTime = dateFormat.format(order.getAddTime());
            completedOrderDTO.setAddTime(addTime);
            completedOrderDTO.setCancelStatus(order.getInvoiceType());
            completedOrderDTO.setNetDeposit(order.getOrderType());
            completedOrderDTO.setEstimateDistance(new Double(order.getDriverServiceCharge()).intValue());
            BeanUtils.copyProperties(order,completedOrderDTO);

            ShipperDTO shipperDTO = userService.queryByShipperIdentityId(order.getConsignorUserId()).getData();
            completedOrderDTO.setShipperName(shipperDTO.getUserName());
            completedOrderDTO.setShipperTelephone(shipperDTO.getTelephone());

            CargoInfoDTO cargoInfoDTO = cargoService.queryCargoInfobyCargoId(order.getCargoId());
            BeanUtils.copyProperties(cargoInfoDTO,completedOrderDTO);

            if(order.getStatus() == 6 ){
                completedOrderDTO.setMsg("您已完成运输，等待货主向您支付运费");
            }else if(order.getStatus() == 7){
                completedOrderDTO.setMsg("订单已完成，运费已支付");
            }
            completedOrderDTOS.add(completedOrderDTO);
        }
        return completedOrderDTOS;
    }

    /**
     * 货主已完成列表
     * @param completedOrderRequest
     * @return
     */
    @Override
    public List<CompletedOrderDTO> getCompletedOrdersByShipper(CompletedOrderRequest completedOrderRequest) {
        ShipperDTO shipperDTO = userService.queryByOpenId(completedOrderRequest.getOpenId()).getData();

        List<OrderEntity> orders= orderDao.queryCompletedOrdersByShipper(shipperDTO.getIdentityNo());

        List<CompletedOrderDTO> completedOrderDTOS = new ArrayList<>(orders.size());
        for(OrderEntity order:orders){
            CompletedOrderDTO completedOrderDTO = new CompletedOrderDTO();

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String addTime = dateFormat.format(order.getAddTime());
            completedOrderDTO.setAddTime(addTime);
            completedOrderDTO.setCancelStatus(order.getInvoiceType());
            BeanUtils.copyProperties(order,completedOrderDTO);

            DriverDTO driverDTO = userService.queryDriverInfoByOpenId(order.getCarrierOpenid()).getData();
            log.info("rpc-userService-driverDTO-返回结果：{}",driverDTO);
            completedOrderDTO.setDriverTelephone(driverDTO.getTelephone());
            completedOrderDTO.setDriverName(driverDTO.getUserName());

            CargoInfoDTO cargoInfoDTO = cargoService.queryCargoInfobyCargoId(order.getCargoId());
            log.info("rpc-cargoService-cargoInfoDTO-返回结果：{}",cargoInfoDTO);
            BeanUtils.copyProperties(cargoInfoDTO,completedOrderDTO);

            completedOrderDTO.setShipperTelephone(shipperDTO.getTelephone());
            completedOrderDTO.setShipperName(shipperDTO.getUserName());
            completedOrderDTO.setMsg("已完成");
            completedOrderDTOS.add(completedOrderDTO);
        }
        return completedOrderDTOS;
    }

    /**
     * 货主同意协议
     * @param agreeOrderRequest
     * @return
     */
    @Override
    public List<TransportOrderDTO> agreeOrderByShipper(AgreeOrderRequest agreeOrderRequest) throws IOException {

        int res = orderDao.agreeOrderByShipper(agreeOrderRequest.getOrderNumber(),new Date(),new Date());
        log.info("货主同意协议影响行数{}",res);

//        messageProduceService.produceOrderMsg(agreeOrderRequest.getOrderNumber(),2);


        return queryTransportOrdersByShipper(new TransportOrderRequest(agreeOrderRequest.getOpenId()));
    }

    /**
     * 司机-取消订单
     * @param cancelOrderRequest
     * @return
     */
    @Override
    public List<CanceledOrderDTO> cancelOrderByDriver(CancelOrderRequest cancelOrderRequest) throws IOException {

        int res = orderDao.cancelOrderByDriver(cancelOrderRequest.getOrderNumber(),new Date(),new Date());
        log.info("司机取消订单影响行数：{}",res);

//        Message cancelOrderMsg =
//                Message.normal("fta-training-trade").tag("fta-order").payload(cancelOrderRequest.getOrderNumber()).build();
//        Result mqRes = orderProducer.send(cancelOrderMsg);
//
//        if (mqRes.getStatus() == ResultStatus.SEND_OK){
//            log.info("MQ-发送成功-fta-orderNumber:{}",cancelOrderRequest.getOrderNumber());
//        }else {
//            log.info("MQ-发送失败-fta-orderNumber:{}",cancelOrderRequest.getOrderNumber());
//        }



        return getCanceledOrdersByDriver(new CanceledOrderRequest(cancelOrderRequest.getOpenId()));
    }

    /**
     * 货主拒绝
     * @param refuseOrderRequest
     * @return
     */
    @Override
    public List<CanceledOrderDTO> refuseOrderByShipper(RefuseOrderRequest refuseOrderRequest) throws IOException {

        int res = orderDao.refuseOrderByShipper(refuseOrderRequest.getOrderNumber(),new Date(),new Date());
        log.info("货主拒绝协议影响行数：{}",res);



//        messageProduceService.produceOrderMsg(refuseOrderRequest.getOrderNumber(),20);
        return getCanceledOrdersByShipper(new CanceledOrderRequest(refuseOrderRequest.getOpenId()));
    }

    /**
     * 货主-取消
     * @param cancelOrderRequest
     * @return
     */
    @Override
    public List<CanceledOrderDTO> cancelOrderByShipper(CancelOrderRequest cancelOrderRequest) throws IOException {

        int res = orderDao.cancelOrderByShipper(cancelOrderRequest.getOrderNumber(),new Date(),new Date());

        log.info("货主取消订单:{}，影响行数：{}",cancelOrderRequest.getOrderNumber(), res);

//        Message cancelOrderMsg =
//                Message.normal("fta-training-trade").tag("fta-order").payload(cancelOrderRequest.getOrderNumber()).build();
//        Result mqRes = orderProducer.send(cancelOrderMsg);
//
//        if (mqRes.getStatus() == ResultStatus.SEND_OK){
//            log.info("MQ-发送成功-fta-orderNumber:{}",cancelOrderRequest.getOrderNumber());
//        }else {
//            log.info("MQ-发送失败-fta-orderNumber:{}",cancelOrderRequest.getOrderNumber());
//        }



        return getCanceledOrdersByShipper(new CanceledOrderRequest(cancelOrderRequest.getOpenId()));
    }

    /**
     * 货主-确认收货
     * @param receiveOrderRequest
     * @return
     */
    @Override
    public int receiveOrderByShipper(ReceiveOrderRequest receiveOrderRequest) throws IOException {

        int res = orderDao.receiveOrderByShipper(receiveOrderRequest.getOrderNumber(),new Date(),new Date(), new Date());
        log.info("货主确认收货影响行数：{}",res);
        String cargoId = orderDao.selectCargoIdByOrderNumber(receiveOrderRequest.getOrderNumber());


//        Message shipperReceiveCargoMsg =
//                Message.normal("fta-training-trade").tag("fta-order").payload(receiveOrderRequest.getOrderNumber()).build();
//        Result mqRes = orderProducer.send(shipperReceiveCargoMsg);


        OrderEntity orderEntity = orderDao.queryOrderDetail(receiveOrderRequest.getOrderNumber());
        membershipService.addShipperMembershipMonthDeals(orderEntity.getConsignorOpenid());

        log.info("addShipperMembershipMonthDeals-rpc-货主：{}",orderEntity.getConsignorOpenid());

        cargoService.cargoStatusEdit(orderEntity.getCargoId(),30);


        Double mileage = cargoService.queryCargoInfobyCargoId(orderEntity.getCargoId()).getMileage();

        membershipService.addDriverMembershipMonthMileage(orderEntity.getCarrierOpenid(),Integer.valueOf(mileage.intValue()));

        log.info("addDriverMembershipMonthMileage-rpc-司机{}-里程{}",orderEntity.getCarrierOpenid(),Integer.valueOf(mileage.intValue()));

//        if (mqRes.getStatus() == ResultStatus.SEND_OK){
//            log.info("MQ-发送成功-fta-orderNumber:{}",receiveOrderRequest.getOrderNumber());
//        }else {
//            log.info("MQ-发送失败-fta-orderNumber:{}",receiveOrderRequest.getOrderNumber());
//        }

        return res;
    }

    /**
     * 司机-装货
     * @param loadOrderRequest
     * @return
     */
    @Override
    public List<TransportOrderDTO> loadOrderByDriver(LoadOrderRequest loadOrderRequest) throws IOException {
        int res = orderDao.loadOrderByDriver(loadOrderRequest.getOrderNumber(),new Date(),new Date());

        log.info("司机我已装货影响行数：{}",res);

//        messageProduceService.produceOrderMsg(loadOrderRequest.getOrderNumber(),5);
        return queryTransportOrdersByDriver(new TransportOrderRequest(loadOrderRequest.getOpenId()));
    }

    /**
     * 司机-卸货
     * @param unloadOrderRequest
     * @return
     */
    @Override
    public List<TransportOrderDTO> unloadOrderByDriver(UnloadOrderRequest unloadOrderRequest) throws IOException {
        int res = orderDao.unloadOrderByDriver(unloadOrderRequest.getOrderNumber(),new Date(),new Date());

        log.info("司机我已装货影响行数：{}",res);

//        messageProduceService.produceOrderMsg(unloadOrderRequest.getOrderNumber(),6);
        return queryTransportOrdersByDriver(new TransportOrderRequest(unloadOrderRequest.getOpenId()));
    }

    /**
     * 货主-重新上架
     * @param republishCargoRequest
     * @return
     */
    @Override
    public CargoInfoDTO republishCargo(RepublishCargoRequest republishCargoRequest) {
        orderDao.republishCargo(republishCargoRequest.getCargoId(),new Date());
        CargoInfoDTO cargoInfoDTO = cargoService.queryCargoInfobyCargoId(republishCargoRequest.getCargoId());

        return cargoInfoDTO;
    }

    @Override
    public ColdTruckResponse getColdTruckDataByShipper(ColdTruckRequest coldTruckRequest) {
        OrderEntity orderEntity = orderDao.queryOrderDetail(coldTruckRequest.getOrderNumber());

        ColdTruckTHData coldTruckTHData = coldTruckService.paoMaDeng(orderEntity.getCargoId()).getData();

//        ColdTruckTHData coldTruckTHData = new ColdTruckTHData();

        ColdTruckResponse coldTruckResponse = new ColdTruckResponse();

        if(Objects.nonNull(coldTruckTHData)){
//        if(false){
            BeanUtils.copyProperties(coldTruckTHData,coldTruckResponse);
            return coldTruckResponse;
        }else {
            coldTruckResponse.setAverageTemperature(24.0);
            coldTruckResponse.setAverageHumidity(43.0);

            coldTruckResponse.setCurrentTemperature(24.3);
            coldTruckResponse.setCurrentHumidity(42.5);

            return coldTruckResponse;
        }

    }
}
